﻿using System.IO;
using System;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Runtime.Serialization;

namespace Fx.Serialization
{
    public class JsonSerializer
    {
        public T Deserialize<T>(string fullFilePath) where T : class
        {
            var formatter = new DataContractJsonSerializer(typeof(T));
            try
            {
                using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    var cache = formatter.ReadObject(fs);
                    return cache as T;
                }
            }
            catch (Exception ex)
            {
                //Logger.LogError(ex);
            }
            return default(T);
        }

        public void Serialize(string fullFilePath, object graph)
        {
            if (graph == null) return;

            var graphType = graph.GetType();
            var formatter = new DataContractJsonSerializer(graphType);
            try
            {
                using (var fs = new FileStream(fullFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                {
                    formatter.WriteObject(fs, graph);
                    fs.Flush();
                    fs.Close();
                }
            }
            catch (Exception)
            {
                //Logger.LogError(ex);
            }
        }

        public string Serialize(object graph)
        {
            if (graph == null) return string.Empty;

            var graphType = graph.GetType();
            var formatter = new DataContractSerializer(graphType);
            try
            {
                var ms = new MemoryStream();
                var writer = JsonReaderWriterFactory.CreateJsonWriter(ms);
                formatter.WriteObject(writer, graph);
                writer.Flush();
                var json = Encoding.Default.GetString(ms.GetBuffer());
                ms.Flush();
                ms.Close();
                writer.Close();
                return json;
            }
            catch (Exception)
            {
                //Logger.LogError(ex);
            }
            return string.Empty;
        }
    }
}
